package com.im.db;

import java.util.ArrayList;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.core.sdk.core.LogUtil;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DBHelper extends OrmLiteSqliteOpenHelper {

	private static final String tag = DBHelper.class.getSimpleName();
	private static final String DATA_BASE_NAME = "lg.db";
	private static final int DATA_BASE_VERSION = 8;

	public DBHelper(Context context) {
		super(context, DATA_BASE_NAME, null, DATA_BASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		LogUtil.e(tag, "onCreate()...");
		createTables(connectionSource);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
		LogUtil.e(tag, "onUpgrade(), oldVersion=" + oldVersion + " newVersion=" + newVersion);
		createTables(connectionSource);
	}

	private void createTables(ConnectionSource connectionSource) {
		ArrayList<Class<?>> classList = TableModelList.getTableClassList();
		for (Class<?> c : classList) {
			try {
				TableUtils.dropTable(connectionSource, c, true);
				TableUtils.createTable(connectionSource, c);
				LogUtil.d(tag, "table " + c.getSimpleName() + " created");
			} catch (Exception e) {
				LogUtil.e(tag, "create Table <" + c.getSimpleName() + "> Exception:", e);
			}
		}
	}

}
